package com.hunter.sign.server.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hunter.common.base.BaseController;
import com.hunter.common.util.CodeUtil;
import com.hunter.common.util.EhCacheUtil;
import com.hunter.common.util.PropertiesFileUtil;
import com.hunter.sign.common.constant.SignConstant;
import com.hunter.sign.common.constant.SignResult;
import com.hunter.sign.common.constant.SignResultConstant;
import com.hunter.sign.common.util.ParamProcess;
import com.hunter.sign.common.util.biometrics.BmpConver;
import com.hunter.sign.common.util.biometrics.CFingerUtils;
import com.hunter.sign.dao.model.SignContract;
import com.hunter.sign.dao.model.SignDevice;
import com.hunter.sign.dao.model.SignDeviceExample;
import com.hunter.sign.dao.model.SignUser;
import com.hunter.sign.dao.model.SignUserContract;
import com.hunter.sign.dao.model.SignUserExample;
import com.hunter.sign.dao.model.SignWitness;
import com.hunter.sign.dao.model.SignWitnessExample;
import com.hunter.sign.rpc.api.SignContractService;
import com.hunter.sign.rpc.api.SignDeviceService;
import com.hunter.sign.rpc.api.SignUserContractService;
import com.hunter.sign.rpc.api.SignUserService;
import com.hunter.sign.rpc.api.SignWitnessService;
import com.hunter.sign.server.vo.request.UserIntroReq;
import com.hunter.sign.server.vo.request.UserLoginReq;
import com.hunter.sign.server.vo.request.UserRegisterReq;
import com.hunter.sign.server.vo.response.UserIntroResp;
import com.hunter.sign.server.vo.response.UserLoginResp;


/**
 * 用户
 * 
 * @author hunter
 * 
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private SignUserService signUserService;

	@Autowired
	private SignWitnessService signWitnessService;
	
	@Autowired
	private SignDeviceService signDeviceService;

	@Autowired
	private SignContractService signContractService;
	
	@Autowired
	private SignUserContractService signUserContractService;
	
	/**
	 * 用户进入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/into", method = RequestMethod.POST)
	public void intro(HttpServletRequest request, HttpServletResponse response, UserIntroReq userIntroReq) {
		logger.info("用户进入，req：" + userIntroReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(userIntroReq, UserIntroReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//通过证件号检索用户
		SignUserExample example = new SignUserExample();
		example.createCriteria()
        	.andIdTypeEqualTo(userIntroReq.getIdType())
        	.andIdCardEqualTo(userIntroReq.getIdCard());
		SignUser signUser = signUserService.selectFirstByExample(example);
		
		UserIntroResp userIntroResp = new UserIntroResp();
		//用户不存在
		if(signUser == null){
			userIntroResp.setRegisterState(0);
		}else{
			userIntroResp.setRegisterState(1);
		}
		logger.info("用户进入，signUser.getRegister：" + userIntroResp.getRegisterState());
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, userIntroResp));
	}
	
	/**
	 * 注册
	 * 
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public void register(HttpServletRequest request, HttpServletResponse response, UserRegisterReq userRegisterReq) {
		logger.info("用户注册，req：" + userRegisterReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(userRegisterReq, UserRegisterReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//指纹识别
		String dsetImg = userRegisterReq.getFingerprintImg().replace(".bmp", "")+"conver.bmp";
	    BmpConver.conver(userRegisterReq.getFingerprintImg(), dsetImg);
		if(CFingerUtils.match(dsetImg, dsetImg)<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNRECOGNIZED_USER_FINGER, null));
			return;
		}
		String dsetImg2 = userRegisterReq.getWitnessFingerprintImg().replace(".bmp", "")+"conver.bmp";
	    BmpConver.conver(userRegisterReq.getWitnessFingerprintImg(), dsetImg2);
		if(CFingerUtils.match(dsetImg2, dsetImg2)<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNRECOGNIZED_WITNESS_FINGER, null));
			return;
		}
		logger.info("用户注册，req：" + userRegisterReq);
		//通过证件号检索用户
		SignUserExample example = new SignUserExample();
		example.createCriteria()
        	.andIdTypeEqualTo(userRegisterReq.getIdType())
        	.andIdCardEqualTo(userRegisterReq.getIdCard());
		SignUser signUser = signUserService.selectFirstByExample(example);
		//用户已注册
		if(signUser != null){
			outHttpJson(response, new SignResult(SignResultConstant.ALREGISTER_USER, null));
			return;
		}
		//注册用户
		signUser = new SignUser();
		signUser.setRealname(userRegisterReq.getRealname());
		signUser.setIdType(userRegisterReq.getIdType());
		signUser.setIdCard(userRegisterReq.getIdCard());
		signUser.setIdFront(userRegisterReq.getIdFront());
		signUser.setIdBack(userRegisterReq.getIdBack());
		signUser.setVideoInfo(userRegisterReq.getVideoInfo());
		signUser.setFingerprintImg(dsetImg);
		signUser.setFingerprintVerify(userRegisterReq.getFingerprintVerify());
		signUser.setCreateTime(System.currentTimeMillis());
		
		//获取见证员信息
		SignWitnessExample signWitnessExample = new SignWitnessExample();
		signWitnessExample.createCriteria()
		.andIdTypeEqualTo(userRegisterReq.getWitnessIdType())
		.andIdCardEqualTo(userRegisterReq.getWitnessIdCard());
		SignWitness signWitness = signWitnessService.selectFirstByExample(signWitnessExample);
		//见证员不存在
		if(signWitness == null){
			outHttpJson(response, new SignResult(SignResultConstant.UNKNOWN_WITNESS, null));
			return;
		}
		
		//见证员指纹信息不符
		if(CFingerUtils.match(dsetImg2, signWitness.getFingerprintImg())<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNMATCH_WITNESS, null));
			return;
		}
		signUser.setWitnessId(signWitness.getWitnessId());
		
		//获取设备信息
		SignDeviceExample signDeviceExample = new SignDeviceExample();
		signDeviceExample.createCriteria()
		.andDevnoEqualTo(userRegisterReq.getDevno());
		SignDevice signDevice = signDeviceService.selectFirstByExample(signDeviceExample);
		//设备不存在
		if(signDevice == null){
			outHttpJson(response, new SignResult(SignResultConstant.UNKNOWN_DEVICE, null));
			return;
		}
		signUser.setDeviceId(signDevice.getDeviceId());
		
		signUserService.insertSelective(signUser);
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, null));
	}
	
	/**
	 * 登录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response, UserLoginReq userLoginReq) {
		logger.info("用户登录，req：" + userLoginReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(userLoginReq, UserLoginReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//指纹识别
		String dsetImg = userLoginReq.getFingerprintImg().replace(".bmp", "")+"conver.bmp";
	    BmpConver.conver(userLoginReq.getFingerprintImg(), dsetImg);
		if(CFingerUtils.match(dsetImg, dsetImg)<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNRECOGNIZED_USER_FINGER, null));
			return;
		}
		//通过证件号检索用户
		SignUserExample example = new SignUserExample();
		example.createCriteria()
        	.andIdTypeEqualTo(userLoginReq.getIdType())
        	.andIdCardEqualTo(userLoginReq.getIdCard());
		SignUser signUser = signUserService.selectFirstByExample(example);
		//用户不存在
		if(signUser == null){
			outHttpJson(response, new SignResult(SignResultConstant.UNKNOWN_USER, null));
			return;
		}
		//用户指纹信息不符
		if(CFingerUtils.match(dsetImg, signUser.getFingerprintImg())<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNMATCH_USER, null));
			return;
		}
		UserLoginResp userLoginResp = new UserLoginResp();
		String token = CodeUtil.createAppToken();
		userLoginResp.setToken(token);
		//生成用户合同记录
		SignUserContract signUserContract = new SignUserContract();
		signUserContract.setCreateTime(System.currentTimeMillis());
		signUserContract.setState(0);
		signUserContract.setUserId(signUser.getUserId());
		signUserContractService.insertSelective(signUserContract);
		userLoginResp.setUserContractId(signUserContract.getUserContractId());
		signUserContract.setContractId(1L);
		SignContract signContract = signContractService.selectByPrimaryKey(1L);
		userLoginResp.setContractPath(PropertiesFileUtil.getInstance("config").get("file.url")+"/templet"+"/"+signContract.getTempletPath());
		userLoginResp.setFieldFill(signContract.getFieldFill());
		//加入ehcache缓存
		EhCacheUtil.put(SignConstant.TOKEN_CACHE, token, signUser.getUserId());
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, userLoginResp));
	}
	
//	public void getYqInvoicePdf(HttpServletRequest request,HttpServletResponse response) {
//		// 下载本地文件
//		String fileName = System.getProperty("cokemeti.root")+"/WEB-INF/classes/temp/xx.pdf";
//        
//        try {
//        	// 读到流中
//            InputStream inStream = new FileInputStream(fileName);// 文件的存放路径
//            // 设置输出的格式
//            response.reset();
//            response.setContentType("application/pdf");
//            response.addHeader("Content-Disposition", "attachment; filename=\"" + new String("xx.pdf".getBytes("utf-8"),"ISO8859-1") + "\"");
//            // 循环取出流中的数据
//            byte[] b = new byte[100];
//            int len;
//            while ((len = inStream.read(b)) > 0)
//                response.getOutputStream().write(b, 0, len);
//            inStream.close();
//        } catch (FileNotFoundException e1) {
//			e1.printStackTrace();
//		} catch (IOException e) {
//            e.printStackTrace();
//        }
//	}
}
